﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Formatters.Binary;
using System.Text;
using System.Threading.Tasks;
using DailyDiet.Models;
using DailyDiet.Services;

namespace DailyDiet.Services.Impl
{
    public class DietsSerializeService : IDietsSerializeService {
        private BinaryFormatter _serializer;

        public BinaryFormatter Serializer =>
            _serializer ?? (_serializer = new BinaryFormatter());

        private static readonly string filePath =
            Environment.GetFolderPath(Environment.SpecialFolder
                .LocalApplicationData);
        public async Task SerializeAsync(List<List<Diet>> diets, string fileName) {
            using (var fileStream = new FileStream(Path.Combine(filePath, fileName), FileMode.OpenOrCreate)) {
                try {
                    Serializer.Serialize(fileStream, diets);
                } catch (Exception e) {
                    Console.WriteLine(e);
                    throw;
                }
            }
        }

        public async Task<List<List<Diet>>> DeSerializeAsync(string fileName) {
            using (FileStream fileStream =
                new FileStream(Path.Combine(filePath, fileName),FileMode.OpenOrCreate)) {
                List<List<Diet>> diets =
                    Serializer.Deserialize(fileStream) as List<List<Diet>>;
                return diets;
            }
        }
    }
}
